package com.qf.lanzhou.blog.api.dao.Impl.login;

import com.qf.lanzhou.blog.api.common.Common;
import com.qf.lanzhou.blog.api.dao.UserDao;
import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.util.BeanProcessor;
import com.qf.lanzhou.blog.api.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.management.relation.Role;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author LEON-HE
 */
public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
    @Override
    public User selectUserByUserName(String userName) {
        String sql = "SELECT * FROM t_user WHERE user_name = ?;";
        BeanHandler<User> handler = BeanProcessor.getBeanHandler(User.class);
        User user = null;
        try {
            user = queryRunner.query(sql,handler,userName);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public Boolean selectUserByPhone(String phone) {
        String sql = "SELECT * FROM t_user WHERE phone = ?;";
        BeanHandler<User> handler = BeanProcessor.getBeanHandler(User.class);
        try {
            User user = queryRunner.query(sql,handler,phone);
            if (user==null){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public String selectUserNameByPhone(String phone) {
        String sql = "SELECT * FROM t_user WHERE phone = ?;";
        BeanHandler<User> handler = BeanProcessor.getBeanHandler(User.class);
        try {
            User user = queryRunner.query(sql,handler,phone);
            if (user!=null){
                return user.getUserName();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean saveUser(User user) {
        Connection conn = null;
        try {
            conn = DruidUtil.getDataSource().getConnection();
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Object[] innerUser = {user.getUserName(),user.getPhone(),user.getEmail()
                                ,user.getAge(),user.getPassword(),user.getSex()};
        String sql_user = "INSERT INTO t_user (user_name,phone,email,age,password,sex) VALUES(?,?,?,?,?,?);";
        String sql_name = "SELECT * FROM t_user WHERE user_name = ?;";
        String sql_role = "INSERT INTO r_user_role (user_id,role_id) VALUES(?,?);";
        BeanHandler<User> handlerUser = BeanProcessor.getBeanHandler(User.class);
        BeanHandler<Role> handlerRole = BeanProcessor.getBeanHandler(Role.class);
        try {
            conn.setAutoCommit(false);
            System.out.println("1");
            queryRunner.insert(conn,sql_user,handlerUser,innerUser);
            System.out.println("2");
            User newUser = queryRunner.query(conn,sql_name,handlerUser,user.getUserName());
            System.out.println("3");
            Object[] innerRole = {newUser.getId(),Common.NORMAL_USER_ROLE_ID};
            queryRunner.insert(conn,sql_role,handlerRole,innerRole);
            conn.commit();
            conn.close();
            return true;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean deleteUserByUserId(Long id) {
        return null;
    }

    @Override
    public Boolean updateUserByUserId(Long id) {
        return null;
    }

    @Override
    public int deleteUserByUserName(String userName) {
        String sql="DELETE FROM t_user WHERE user_name =? ";
        User user = selectUserByUserName(userName);
        Long id = user.getId();
        String sq2="DELETE FROM r_user_role WHERE user_id=? ";
        int query=0;
        try {
            query = queryRunner.update(sql, userName);
            query =queryRunner.update(sq2,id);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return query;
        }

    }

    @Override
    public List<User> showUserList() {
        String sql="SELECT user_name,last_login_time FROM t_user";
        BeanListHandler beanListHandler = BeanProcessor.getBeanListHandler(User.class);
        List<User> query=null;
        try {
            query = (List<User>) queryRunner.query(sql, beanListHandler);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Boolean updateLoginTime(String name) {
        String sql="UPDATE t_user SET last_login_time=? WHERE user_name=?;";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(new Date());
        Object[] updateParam = {date,name};
        try {
            queryRunner.update(sql,updateParam);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public int updatePassword(String password, String userName ) {
        String sql="UPDATE t_user SET password = ? WHERE user_name = ? ";
        Object[] params={password,userName};
        int query=0;
        try {
            query = queryRunner.update(sql,params);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
            return query;
        }
    }

    @Override
    public int udateMsg(String email, String phone, User user) {
        String sql="UPDATE t_user SET email = ? WHERE user_name = ? ";
        String sq2="UPDATE t_user SET phone = ? WHERE user_name = ? ";
        String sq3="UPDATE t_user SET email = ?,phone = ? WHERE user_name = ? ";
        Object[] params={email,phone,user.getUserName()};
        int query=0;
        //判断修改内容,邮箱为空，修改电话
        if (email.trim().equals("")||email==null){
            try {
                query = queryRunner.update(sq2, phone, user.getUserName());
                return query;
            } catch (SQLException e) {
                e.printStackTrace();
                return query;
            }
        }
        ////判断修改内容,电话为空，修改邮箱
        if (phone.trim().equals("")||phone==null){
            try {
                query = queryRunner.update(sql, email, user.getUserName());
                return query;
            } catch (SQLException e) {
                e.printStackTrace();
                return query;
            }
        }
        //都不为空，两样修改
        try {
            query=queryRunner.update(sq3,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }return query;
    }

    @Override
    public Long checkAdmin(String sql, Long userId) {
        Long num=0L;
        try {
            num=queryRunner.query(sql,new ScalarHandler<Long>(),userId);
            if (num==null||num==0L){
              return 0L;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public int updateUserRole(Long userId) {
        String sql="INSERT INTO r_user_role (user_id, role_id) VALUES (?, 100) ;";
        int update=0;
        try {
            update = queryRunner.update(sql, userId);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }

    @Override
    public Long checkAminFull(String sql) {
        Long num=0L;
        try {
            num=queryRunner.query(sql,new ScalarHandler<Long>());
            if (num==null||num==0){
                return 0L;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public List<User> selectAllExclusionUser(String name) {
        String sql = "SELECT * FROM `t_user` WHERE user_name != ?;";
        Object[] parm = {name};
        BeanListHandler handler = BeanProcessor.getBeanListHandler(User.class);
        try {
            List list = (List) queryRunner.query(sql, handler, parm);
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

}
